import React, { useEffect, useReducer } from "react";

let initCount = 0;

function reducer(state, action) {
  switch (action.type) {
    case "add":
      return { count: state.count + 1 };
      break;
    case "decrement":
      return { count: state.count - 1 };
      break;
    default:
      break;
  }
}

function init() {
  console.log(9);
  return { count: initCount };
}

let count = 0;

export const UseReducerComp = (props) => {
  console.log(++count, "render");
  const [state, dispatch] = useReducer(reducer, initCount, init);

  const handleClick = (index) => {
    if (index === 1) {
      return dispatch({
        type: "add",
      });
    }

    return dispatch({
      type: "decrement",
    });
  };

  useEffect(() => {
    const fn = () => {
      // let i = count + 1;
      console.log(state, "fn");
      return state;
    };
    const ret = fn();
    console.log(ret);
    console.log("useEffect");
  }, [state]);
  return (
    <>
      <p>{state.count}</p>
      <button onClick={() => handleClick(1)}>增加</button>
      <button onClick={() => handleClick(2)}>减少</button>
      {/* <p>{count1}</p>
      <button onClick={handleClick}>点我1</button> */}
    </>
  );
};

// export const UseReducerComp;
